package polimi.sc.expoquest.screen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import polimi.sc.expoquest.R;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;


public class CameraActivity extends Activity {
	public final static String DEBUG_TAG = "SingleplayCameraActivity";
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final String EXPO_QUEST = "ExpoQuestCamera";
	public static final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	private String fileName;
	private Camera camera;
	
	private int cameraId = 0;
	
	private CameraPreview mPreview; 
	private PictureCallback mPicture = new PictureCallback() {
	
	    @Override
	    public void onPictureTaken(byte[] data, Camera camera) {

	        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);	       
	        if (pictureFile == null){
	            Log.d(DEBUG_TAG, "Error creating media file, check storage permissions: ");
	            return;
	        }

	        try {
	        	
	            FileOutputStream fos = new FileOutputStream(pictureFile);
	            fos.write(data);
	            fos.close();
	    		Intent intent = new Intent();
	    		intent.putExtra("fileName", fileName);
	    		setResult(RESULT_OK,intent);
	    		finish();
	        } catch (FileNotFoundException e) {
	            Log.d(DEBUG_TAG, "File not found: " + e.getMessage());
	        } catch (IOException e) {
	            Log.d(DEBUG_TAG, "Error accessing file: " + e.getMessage());
	        }
	    }
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera);
		// do we have a camera?
	    if (!getPackageManager()
	        .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
	      Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
	          .show();
	    } else {
	      cameraId = findCamera();
	      if (cameraId < 0) {
	        Toast.makeText(this, "No camera found.",
	            Toast.LENGTH_LONG).show();
	      } else {
	        camera = Camera.open(cameraId);
	        mPreview = new CameraPreview(this, camera);
	        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
	        preview.addView(mPreview);
	      }
	    }
	}
	private int findCamera() {
	    int cameraId = -1;
	    // Search for the front facing camera
	    int numberOfCameras = Camera.getNumberOfCameras();
	    for (int i = 0; i < numberOfCameras; i++) {
	      CameraInfo info = new CameraInfo();
	      
	      Camera.getCameraInfo(i, info);
	        Toast.makeText(this, "camera found"+info.facing ,
		            Toast.LENGTH_LONG).show();
	      if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
	        Log.d(DEBUG_TAG, "Camera found");
	        cameraId = i;

	        break;
	      }
	    }
	    return cameraId;
	  }
	public void takepicturePressed(View v)
	{
		
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), EXPO_QUEST);    		    
	    fileName = mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg";
	    
		    	    			 
		if (camera != null)
			camera.takePicture(null, null,mPicture);

	}
	 @Override
	 protected void onPause() {
	    if (camera != null) {
	      camera.release();
	      camera = null;
	    }
	    super.onPause();
	  }
		/** Create a File for saving an image or video */
		private static File getOutputMediaFile(int type){
		    // To be safe, you should check that the SDCard is mounted
		    // using Environment.getExternalStorageState() before doing this.

		    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
		              Environment.DIRECTORY_PICTURES), EXPO_QUEST);
		    // This location works best if you want the created images to be shared
		    // between applications and persist after your app has been uninstalled.
		    
		    		    
		    // Create the storage directory if it does not exist
		    if (! mediaStorageDir.exists()){
		        if (! mediaStorageDir.mkdirs()){		            		        
		        	Log.d(EXPO_QUEST, "failed to create directory");
		            return null;
		        }
		    }

		    // Create a media file name
//		    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//		    fileName = mediaStorageDir.getPath() + File.separator +
//			        "IMG_"+ timeStamp + ".jpg";
		    File mediaFile;
		    if (type == MEDIA_TYPE_IMAGE){		    	
		    	mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
		        
		        
		    } 
		     else {
		        return null;
		    }

		    return mediaFile;
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_camera, menu);
		return true;
	}

}
